<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in" ref="dialogBox">
      <div class="cornerComment-in-title">
        <span v-if="orderType==1">采购下单</span>
        <span v-if="orderType==2">物料入库</span>
        <span v-if="orderType==3">教具入库</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody">
        <div class="apply-box-right" :style="{height: tableHeight+'px'}" v-if="JSON.stringify(purchase)!=='{}'">
          <div class="apply-box-right-list" v-for="(item,index) in purchase" :key="index">
            <div class="apply-box-right-list-box">
              <div class="rightapply-box-right-list-box-img">
                <div class="rightapply-box-right-list-box-img-in"
                     :style="{backgroundImage:'url('+item.pic+')',backgroundSize:'cover',backgroundPosition:'center'}"
                     @click="actionSheet('list', index)">
                  <i class="el-icon-camera-solid" v-if="!item.pic"></i>
                  <span v-if="!item.pic && (orderType==2 || orderType==3)" class="el-icon-camera-solid-text">入库照</span>
                </div>
                <div class="rightapply-box-right-list-box-img-title">
                  <p>{{ item.name }}</p>
                  <p>{{ item.reason }}</p>
                </div>
              </div>
              <div class="rightapply-box-right-list-box-number">
                <!--                <span class="el-icon-remove-outline" @click="addSub(1,index)"></span>-->
                <i class="num-line">数量：</i>
                <el-input v-model="item.need_number" placeholder="数量" size="small"  v-if="orderType==1"></el-input>
                <el-input v-model="item.need_number" placeholder="数量" size="small"  v-else readonly></el-input>
                <!--                <span class="el-icon-circle-plus-outline" @click="addSub(2,index)"></span>-->
              </div>
              <div class="rightapply-box-right-list-box-price" v-if="Number(orderType)==1 || Number(orderType)==3">
                {{ item.price ? item.price : '--' }} <span>元</span>
              </div>
              <div class="rightapply-box-right-list-box-price" v-if="Number(orderType)==2">
                <el-select v-model="item.warehouse_id" placeholder="请选择仓库" size="small">
                  <el-option
                      v-for="item in warehouseList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="detele-box el-icon-error" @click="deleteFn(index)"></div>
            </div>
          </div>
        </div>
        <div class="apply-box-right" :style="{height: tableHeight+'px'}" v-else>
          <div class="apply-nonedata">暂无{{ orderType == 1 ? '下单' : '入库' }}物件</div>
        </div>
        <div class="footer-apply" v-if="Number(orderType)==1">
          <span>{{ applyBookBoxNumber_.length }}件 总价</span><span class="price">{{ count }}</span><span>元</span>
        </div>
      </div>
      <div class="cornerComment-in-footer">
        <el-button @click.native="closePOpup" size="small">取消</el-button>
        <el-button size="small" @click="clearList">一键清空</el-button>
        <el-button size="small" type="primary" @click="checkEditFn">{{ Number(orderType) == 1 ? '确定下单' : '确定入库' }}
        </el-button>
      </div>
    </div>
    <form style="display: none" enctype="multipart/form-data">
      <input type="file" accept="image/*" @change="handleFile('pic')" class="hiddenInput" id="uploadFile"
             ref="uploadFile"/>
    </form>
    <AuxiliaryModule @getInformation="getInformation" :typeData="typeData" :optionData="purchase"></AuxiliaryModule>
  </div>
</template>

<script>
// <!--    orderType 1 下单 2 物料入库 3 教具入库-->
export default {
  props: ['visible', 'applyBookBox', 'applyBookBoxNumber', 'orderType'], // recruitmentType examine 审核
  components: {},
  data() {
    return {
      typeData: 'warehousing',
      dialogVisible: false,
      purchase: {},
      infoForm: {
        name: '',
        cate_id: '',
        reason: '',
        unit: '', // "单位",
        need_number: 1,
        price: '',
        pic: '',
        url: '',
        expect_time: '',
        remark: '',
        cate_son_id: ''
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      tableHeight: 0,
      applyBookBoxNumber_: [],
      count: 0,
      warehouseList: []
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        let n = this;
        // <!--    orderType 1 下单 2 物料入库 3 教具入库-->
        let b = this.getJson(this.applyBookBox)
        if (Number(this.orderType) === 2 || Number(this.orderType) === 3) {
          for (let i in b) {
            b[i].pic = ''
          }
        }
        this.purchase = b
        this.applyBookBoxNumber_ = this.getJson(Object.keys(this.purchase))

        if (Number(this.orderType) === 1) {
          this.countPrice()
          this.$nextTick(() => {
            let height = n.$refs.dialogBox.offsetHeight;  //top 50 1 search 50 page 50 10 footer 50 1
            this.tableHeight = height - (51 + 20 + 40 + 51)
          })
        }
        if (Number(this.orderType) === 2 || Number(this.orderType) === 3) {
          // 物料入库获取仓库
          this.getWarehouse()
          this.$nextTick(() => {
            let height = n.$refs.dialogBox.offsetHeight;  //top 50 1 search 50 page 50 10 footer 50 1
            this.tableHeight = height - (51 + 20 + 51)
          })
        }
      } else {
        this.purchase = {};
        this.applyBookBoxNumber_ = [];
      }
    }
  },
  created() {

  },
  methods: {
    async checkEditFn() {
      // list id 采购id actual_number 实际数量 pay_price 购买价格
      console.log('purchase:', this.purchase)
      let list = [];
      for (let i in this.purchase) {
        let a = {};
        a.id = i;
        // 下单
        if (Number(this.orderType) === 1) {
          a.actual_number = this.purchase[i].need_number;
          a.pay_price = this.purchase[i].price;
        }
        // 物料入库
        if (Number(this.orderType) === 2) {
          a.number = this.purchase[i].need_number;
          if (!this.purchase[i].warehouse_id) {
            this.$message.error('请选择仓库')
            return
          }
          a.warehouse_id = this.purchase[i].warehouse_id;
          a.pic = this.purchase[i].pic;
        }
        // 教具入库
        if (Number(this.orderType) === 3) {
          a.number = this.purchase[i].need_number;
          a.warehouse_id = 0;
          a.pic = this.purchase[i].pic;
        }
        list.push(a)
      }
      let api_ = this.api.purchase.order; // 下单
      // // <!--    orderType 1 下单 2 物料入库 3 教具入库-->
      if (Number(this.orderType) === 2 || Number(this.orderType) === 3) {
        api_ = this.api.purchase.put;
      }
      if (!list.length) {
        // <!--    orderType 1 下单 2 物料入库 3 教具入库-->
        this.$message.error(`请选择需要${this.orderType == 1 ? '下单' : '入库'}的物件`)
        return
      }
      console.log('list:', list)
      // let status = 1
      // if(status){
      //   return
      // }
      let data = await this.$post(api_, {list: JSON.stringify(list)});
      if (!data.code) {
        this.$message.success(Number(this.orderType) === 1 ? '下单成功！' : '入库成功！')
        this.applyBookBoxNumber_ = [];
        this.purchase = {};
        this.count = 0;
        this.$emit('clearList', {type: 'pay'})
        if (Number(this.orderType) === 1) {
          this.countPrice()
        }
        if (Number(this.orderType) === 2 || Number(this.orderType) === 3){
          this.$emit('getNewList')
        }
      }
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    clearList() {
      this.applyBookBoxNumber_ = [];
      this.purchase = {};
      this.count = 0;
      this.$emit('clearList', {type: 'clear'})
      this.countPrice()
    },
    deleteFn(index) {
      // let list = this.getJson(this.purchase)
      this.applyBookBoxNumber_.splice(this.applyBookBoxNumber_.indexOf(index), 1)
      delete this.purchase[index]
      this.purchase = Object.assign({}, this.purchase) // 更新视图对象
      console.log('index:', index, this.purchase)
      this.$emit('clearList', {type: 'delete', index: index})
      this.countPrice()
    },
    countPrice() {
      let count = 0;
      console.log('this.purchase:', this.purchase)
      for (let i in this.purchase) {
        count = count + parseFloat(this.purchase[i].price) * Number(this.purchase[i].need_number);
      }
      this.count = count;
    },
    async getWarehouse() {
      let data = await this.$fetch(this.api.mater.warehouse.index, {p: 1});
      console.log('仓库详情', data)
      this.warehouseList = data.list.data
    },
    addSub(type, index) {
      // type 1 减 2 加
      let option = this.getJson(this.purchase[index])
      if (type === 1) {
        if (option.need_number === 1) {
          return
        }
        if (Number(option.need_number) > 1) {
          option.need_number = Number(option.need_number) - 1;
        }
      } else {
        option.need_number = Number(option.need_number) + 1;
      }
      this.$set(this.purchase, index, option)
      this.countPrice()
    },
    actionSheet(option, index) {
      // option add 添加 list 列表编辑
      // if (option === 'qr_code' && this.familyImg.length >= 4) {
      //   Toast('图片最大限制')
      //   return
      // }
      // console.log('图片最大限制')
      // <!--    orderType 1 下单 2 物料入库 3 教具入库-->
      if (Number(this.orderType) === 2 || Number(this.orderType) === 3) {
        this.imgType = option;
        this.picIndex = index;
        this.$el.querySelector('.hiddenInput').click()
      }
      // 来回切换 type 使得能够上传同一张图
      // setTimeout(()=>{
      //   this.$el.querySelector('.hiddenInput').setAttribute('type','text')
      // },200)
    },
    async handleFile(option) {
      // 此处不能使用event.target，否则手机上不能显示
      let n = this;
      let file = document.querySelector('#uploadFile')
      let formData = new FormData()
      if (file.files[0]) {
        // Indicator.open('上传中…')
        formData.append('file', file.files[0])
        // 接下来就可以用 ajax 提交 formData
        let data = await this.$post('upload/oldupload', formData);
        console.log('data:', data)
        if (!data.code) {
          // this.imgUpload[this.imgType] = data.pic
          // console.log('this.imgUpload:', this.imgUpload)
          let list = n.getJson(n.purchase[n.picIndex])
          list.pic = data.data.name;
          n.$set(n.purchase, n.picIndex, list)
          n.$refs.uploadFile.value = ''
          // 来回切换 type text file 以便能够上传选择同一张图
          // setTimeout(() => {
          //   // Indicator.close()
          //   n.$el.querySelector('.hiddenInput').setAttribute('type','file')
          // }, 300)
        }
      }
    },
    // 同步数据
    getInformation(option) {
      console.log('收到的数据内容：', option)
      for (let item of option) {
        if (item.type === 'img' && item.number === 1) {
          this.purchase[item.id].pic = item.value[0].url
        }
      }
    }
  },
  mounted() {
  }
}
</script>
<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 500px;
  height: 70%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: flex-end;
}

.commentBody {
  padding: 10px;
  flex: 1;
  overflow-y: auto;
}

.close-Btn-line {
  cursor: pointer;
}

.jobTime span {
  padding: 0 10px;
}

.apply-box-right-list {
  margin-bottom: 10px;
  border-bottom: 1px dashed #333;
  padding-bottom: 15px;
  cursor: pointer;
}

.apply-box-right-list:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.apply-box-right-list-top {
  display: flex;
  margin-bottom: 5px;
}

.apply-box-right {
  width: 100%;
  border: 1px solid #999;
  border-radius: 5px;
  background: #ffe5c2;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 20px 10px;
  overflow-y: auto;
}

.apply-box-right-top {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.apply-box-right-list-top div {
  flex: 1;
}

.apply-box-right-list-top div span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 230px;
  display: block;
}

.apply-box-right-list-box {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 10px;
  position: relative;
}

.detele-box {
  position: absolute;
  right: -10px;
  top: -15px;
  font-size: 28px;
  color: red;
}

.detele-box:hover {
  text-decoration: underline;
}

.rightapply-box-right-list-box-img {
  display: flex;
  align-items: center;
  width: 220px;
}

.rightapply-box-right-list-box-img-in {
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f4f4f4;
  margin-right: 10px;
  flex-direction: column;
  font-size: 10px;
  color: #777;
}

.rightapply-box-right-list-box-img-in i {
  font-size: 40px;
  color: #aaa;
}

.rightapply-box-right-list-box-img-title {
  font-size: 16px;
}

.rightapply-box-right-list-box-img-title p:last-child {
  font-size: 14px;
  color: #999;
}

.rightapply-box-right-list-box-number {
  display: flex;
  align-items: center;
  width: 100px;
  margin: 0 10px;
}

.rightapply-box-right-list-box-number span {
  font-size: 22px;
  cursor: pointer;
}

.rightapply-box-right-list-box-number span:hover {
  text-decoration: underline;
}

.rightapply-box-right-list-box-price {
  font-size: 20px;
  flex: 1;
  text-align: center;
}

.rightapply-box-right-list-box-price span {
  font-size: 14px;
}

.rightapply-box-right-list-box-price:hover {
  text-decoration: underline;
}

.footer-apply {
  text-align: right;
  height: 40px;
  line-height: 40px;
  padding-right: 20px;
}

.footer-apply span {
  font-size: 18px;
}

.footer-apply span.price {
  font-size: 24px;
  color: #1aad19;
  padding: 0 5px;
}

.apply-nonedata {
  text-align: center;
  color: #999;
  font-size: 20px;
  padding: 150px 0;
}

.num-line {
  width: 74px;
  font-size: 14px;
  font-style: normal;
}
</style>


